<?php
/**
 * Created by PhpStorm.
 * User: dingjinlai
 * Date: 2019/5/24
 * Time: 上午10:26
 */

class Prepare_goods_model extends CI_Model
{   
    public $limit_rows = 15;

    public function goods_sn_max($admin_id)
    {
        $query = $this->db->from('prepare_goods')->select('goods_sn')->where('admin_id', $admin_id)->order_by('prepare_id desc')->get();

        $info = $query->row_array();

        $query = $this->db->from('admin')->where('admin_id', $admin_id)->get();

        $admin = $query->row_array();

        if ($info) {
            return $admin['ab_name'] . sprintf("%04d", ltrim(preg_replace("/[A-Za-z]+/", '', $info['goods_sn']), '0') + 1);
        } else {
            return $admin['ab_name'] . '2000';
        }
    }

    public function step_1_add($data)
    {
        if($data['production_id'] == 2){
            $time = time();
            $image = $data['images'];
            $_data = array(
                'purchase_id' => $data['purchase_id'],
                'fabric_id' => $data['fabric_id'],
                'goods_sn' => $data['goods_sn'],
                'admin_id' => $data['admin_id'],
                'cate_id' => $data['cate_id'],
                'channel_id' => $data['channel_id'],
                'production_id' => $data['production_id'],
                'original_img' => $image['file_name'],
                'prepare_state' => 1,
                'add_time' => $time,
                // 'g_supp_id' => $data['g_supp_id'],
                'ali_url' => $data['supp_url'],
                'sale_status' => $data['sale_status'],
                'shop_price' => $data['shop_price'],
                'in_price' => $data['in_price'],
                'type_style'=> $data['type_style'],
            );
            $this->db->insert('prepare_goods', $_data);
            $prepare_id = $this->db->insert_id();

            if ($data['ali_sku']) {
                foreach ($data['ali_sku'] as $k => $val) {
                    $_type_id = $k == 'color' ? 1 : 2;
                    foreach ($val as $row) {
                        if ($row['value'] != '') {
                            $_option['insert'][] = array(
                                'prepare_id' => $prepare_id,
                                'type_id' => $_type_id,
                                'option_value' => $row['value'],
                                'ali_value' => $row['ali_value'],
                                'add_time' => $time
                            );
                        }
                    }
                }
            }

            
            if ($_option['insert']) {
                $this->db->insert_batch('prepare_option', $_option['insert']);
            }

            $_goods_supp = array(
                'cn_name' => '定制产品',
                'supp_url' => $data['supp_url'],
                'supp_sn' => 0,
                'in_price' => $data['in_price'],
                'prepare_id' => $prepare_id
            );
            $this->db->insert('goods_supp', $_goods_supp);
            $goods_supp_id = $this->db->insert_id();

            $this->db->where(['prepare_id'=>$prepare_id]);
            $this->db->update('prepare_goods',['g_supp_id'=>$goods_supp_id]);

            if ($prepare_id) {
                $_images = array(
                    'prepare_id' => $prepare_id,
                    'sku_id' => 0,
                    'original_img' => $image['file_name'],
                    'big_img' => '',
                    'small_img' => '',
                    'width' => $image['image_width'],
                    'height' => $image['image_height'],
                    'album_sort' => 1,
                    'is_delete' => 0,
                    'add_time' => $time
                );
                $this->db->insert('goods_album', $_images);
            }
            $this->add_prepare_log(1, 1, '创建产品', $prepare_id);

            return true;

        }else{
            $time = time();
            $image = $data['images'];
            $_data = array(
                'purchase_id' => $data['purchase_id'],
                'fabric_id' => $data['fabric_id'],
                'goods_sn' => $data['goods_sn'],
                'admin_id' => $data['admin_id'],
                'cate_id' => $data['cate_id'],
                'channel_id' => $data['channel_id'],
                'production_id' => $data['production_id'],
                'original_img' => $image['file_name'],
                'prepare_state' => 1,
                'add_time' => $time,

                'ali_url' => $data['supp_url'],
                'g_supp_id' => $data['g_supp_id'],
                'shop_price' => $data['shop_price'],
                //'cn_name' => $data['supp_name'],
                //'supp_sn' => $data['supp_sn'],
                'in_price' => $data['in_price'],
                //'prepare_id' => $prepare_id
                'type_style'=> $data['type_style'],
            );
            $this->db->insert('prepare_goods', $_data);
            $prepare_id = $this->db->insert_id();
            if ($data['ali_sku']) {
                $_goods_supp['post_sku'] = json_encode($data['ali_sku']);
                foreach ($data['ali_sku'] as $k => $val) {
                    $_type_id = $k == 'color' ? 1 : 2;
                    foreach ($val as $row) {
                        if ($row['value'] != '') {
                            $_option['insert'][] = array(
                                'prepare_id' => $prepare_id,
                                'type_id' => $_type_id,
                                'option_value' => $row['value'],
                                'ali_value' => $row['ali_value'],
                                'add_time' => $time
                            );
                        }
                    }
                }
            }
            if ($_option['insert']) {
                $this->db->insert_batch('prepare_option', $_option['insert']);
            }

            // $_goods_supp = array(
            //     'cn_name' => $data['supp_name'],
            //     'supp_url' => $data['supp_url'],
            //     'supp_sn' => $data['supp_sn'],
            //     'in_price' => $data['in_price'],
            //     'prepare_id' => $prepare_id
            // );
            $_goods_supp['cn_name'] = $data['supp_name'];
            $_goods_supp['supp_url'] = $data['supp_url'];
            $_goods_supp['supp_sn'] = $data['supp_sn'];
            $_goods_supp['in_price'] = $data['in_price'];
            $_goods_supp['prepare_id'] = $prepare_id;
            $this->db->where(['g_supp_id'=>$data['g_supp_id']]);
            $this->db->update('goods_supp',$_goods_supp);

            if ($prepare_id) {
                $_images = array(
                    'prepare_id' => $prepare_id,
                    'sku_id' => 0,
                    'original_img' => $image['file_name'],
                    'big_img' => '',
                    'small_img' => '',
                    'width' => $image['image_width'],
                    'height' => $image['image_height'],
                    'album_sort' => 1,
                    'is_delete' => 0,
                    'add_time' => $time
                );
                $this->db->insert('goods_album', $_images);
            }
            $this->add_prepare_log(1, 1, '创建产品', $prepare_id);

            return true;
        }
        
    }

    //准入表 列表
    public function prepare_accurate_list($param = array()){


        if($param['admin_id'] > 0){
            $this->db->where(['admin_id'=>$param['admin_id']]);
        }
        if(!empty($param['goods_sn'])){
            $this->db->where(['goods_sn'=>$param['goods_sn']]);
        }
        if($param['cate_name'] > 0){
            $this->db->where(['cate_id'=>$param['cate_name']]);
        }
        if($param['production'] > 0){
            $this->db->where(['production_id'=>$param['production']]);
        }
        $this->db->where(['prepare_state'=>$param['prepare_state']]);


        if($param['prepare_state'] == 1 || $param['prepare_state'] == 2 || $param['prepare_state'] == 6){
            $len = 'prepare_id,original_img,goods_sn,prepare_state,cate_id,add_time,admin_id,production_id,channel_id';
        }
        
        if($param['prepare_state'] == 3 || $param['prepare_state'] == 4 || $param['prepare_state'] == 5){
            $len = 'prepare_id,original_img,goods_sn,prepare_state,cate_id,add_time,admin_id,
            production_id,source_url,g_supp_id,channel_id,in_price,goods_weight,title,ali_url';
        }
        
        $this->db->from('prepare_goods');
        $this->db->select($len);

        $this->db->limit($this->limit_rows,$this->limit_rows * $param['page']);
        $this->db->order_by('add_time desc');
        $query = $this->db->get();
        $prepare = $query->result_array();
        if(empty($prepare)){
            return $prepare;
        }
        foreach ($prepare as $k => $v) {
            //开发员
            $arr = ['admin_id'=>$v['admin_id']];
            $admin_name = $this->select_find('admin',$arr,'admin_name');
            $prepare[$k]['admin_name'] = $admin_name['admin_name'];
            //查询分类
            $arr = ['cate_id'=>$v['cate_id']];
            $cate_name = $this->select_find('category',$arr,'cate_name');
            $prepare[$k]['cate_name'] = $cate_name['cate_name'];

            $prepare[$k]['add_time'] = date('Y-m-d H:i',$v['add_time']);
            //供应商
            $arr = ['g_supp_id'=>$v['g_supp_id']];
            $g_supp_id = $this->select_find('goods_supp',$arr,'supp_id');
            $suppliers_name = $this->select_find('suppliers',['suppliers_id'=>$g_supp_id['supp_id']],'suppliers_name');
            $prepare[$k]['suppliers_name'] = $suppliers_name['suppliers_name'];
            //供应商货号
            $arr = ['prepare_id'=>$v['prepare_id']];
            $supp_sn = $this->select_find('goods_supp',$arr,'supp_sn');
            $prepare[$k]['supp_sn'] = $supp_sn['supp_sn'];
            if($v['channel_id'] == 1){
                $prepare[$k]['channel_id'] = '外网';
            }
            if($v['channel_id'] == 2){
                $prepare[$k]['channel_id'] = '竞争对手';
            }
            if($v['channel_id'] == 3){
                $prepare[$k]['channel_id'] = '供应商1688';
            }
            //颜色
            $where = ['prepare_id'=>$v['prepare_id'],'is_delete'=>0,'type_id'=>1];
            $len = 'option_value';
            $prepare[$k]['color'] = $this->size_color($where,$len);
            //尺码
            $where = ['prepare_id'=>$v['prepare_id'],'is_delete'=>0,'type_id'=>2];
            $len = 'option_value';
            $prepare[$k]['size'] = $this->size_color($where,$len);
            //审核时间
            
            if($param['prepare_state'] == 4 || $param['prepare_state'] == 5){
                $len = 'add_time';
                if($param['prepare_state'] == 4){
                    $where = ['prepare_id'=>$v['prepare_id'],'current_state'=>4];
                }elseif($param['prepare_state'] == 5){
                    $where = ['prepare_id'=>$v['prepare_id'],'current_state'=>5];
                }
                $add_time = $this->prepare_log($where,$len);
                $prepare[$k]['log_add_time'] = date('Y-m-d H:i',$add_time['add_time']);
            }
           
            //查询未通过和回收商品 待编辑3 和 回收站 6
            if($param['prepare_state'] == 3 || $param['prepare_state'] == 6){
                $arr = ['type_state'=>5,'prepare_id'=>$v['prepare_id']];
                $len = 'add_time,content';
                $order = 'log_id DESC';
                $log_con = $this->select_find('prepare_log',$arr,$len,$order);
                if($log_con){
                    $prepare[$k]['log_existence'] = 1;
                    $prepare[$k]['log_add_time'] = date('Y-m-d H:i',$log_con['add_time']);
                    $prepare[$k]['log_content']  = $log_con['content'];
                }
            }

        }
        return $prepare;
    }

    //提交审核
    //操作类型: 1 创建商品 2 编辑商品 3 补充商品 4 审核通过 5 审核不通过 6 加入回收站 7 撤回回收站 8 添加尺码 9 上架完成 10 加色
    public function examine_goods($data){
        if(!is_array($data['goods_id'])){
            $data['goods_id'] = [$data['goods_id']];
        }
        foreach ($data['goods_id'] as $key => $goods_id) {
            //查询当前产品状态
            $arr = $this->select_find('prepare_goods',['prepare_id'=>$goods_id],'prepare_state');
            //通过
            if($data['is_adopt'] == 1){
                if($arr['prepare_state'] == 4){
                    //上架通过添加goods表 和E 仓
                    $this->prepare_goods_add($goods_id);
                }
                if($arr['prepare_state'] == 1){
                    //修改商品表状态
                    $current_state = $arr['prepare_state'] + 2;
                    $this->db->where(['prepare_id'=>$goods_id]);
                    $this->db->update('prepare_goods',['prepare_state'=>$current_state]);
                    $type_state = 4;
                }else{
                    //修改商品表状态
                    $current_state = $arr['prepare_state'] + 1;
                    $this->db->where(['prepare_id'=>$goods_id]);
                    $this->db->update('prepare_goods',['prepare_state'=>$current_state]);
                    $type_state = 4;
                }
            }
            //不通过
            if($data['is_adopt'] == 2){
                //如果商品状态是1 就是第一步审核 放入到回收站
                if($arr['prepare_state'] == 1){
                    $this->db->where(['prepare_id'=>$goods_id]);
                    $this->db->update('prepare_goods',['prepare_state'=>6]);
                    $current_state = 6;
                    $type_state = 5;
                }else{
                    if($arr['prepare_state'] == 3){
                        //待审核
                        $current_state = $arr['prepare_state'] - 2;
                        $this->db->where(['prepare_id'=>$goods_id]);
                        $this->db->update('prepare_goods',['prepare_state'=>$current_state]);
                        $type_state = 5;
                    }else{
                        //不是第一步审核返回待编辑
                        $current_state = $arr['prepare_state'] - 1;
                        $this->db->where(['prepare_id'=>$goods_id]);
                        $this->db->update('prepare_goods',['prepare_state'=>$current_state]);
                        $type_state = 5;
                    }
                }
            }
            //添加日志记录
            $this->add_log($goods_id,$arr['prepare_state'],$current_state,$type_state,$data['reason_text']);
        }
        return 1;
    }

    //准入表添加到商品表
    public function prepare_goods_add($goods_id){

        $this->load->library('Eccang');

        
        $arr = $this->select_find('prepare_goods',['prepare_id'=>$goods_id],'*');
        //查看这个商品存不存在
        $gid = $this->select_find('goods',['goods_sn'=>$arr['goods_sn']],'goods_id');
        $gid = $gid['goods_id'];
        if(!empty($arr['tags'])){
            $tag = '';
            $tags = $this->db->from('tags')->where_in('id',explode(',',$arr['tags']))->get()->result_array();
            foreach ($tags as $k => $v) {
                $tag = $tag.','.$v['tags_name'];
            }
            $tag = substr($tag,1);
        }
        if(!$gid){
            //查询supp表
            $supp = $this->select_find('goods_supp',['prepare_id'=>$goods_id],'supp_id,supp_sn');
            //$supp_id = $this->select_find('goods_supp',['prepare_id'=>$goods_id],'supp_id');
            $suppliers_id = $this->select_find('suppliers',['suppliers_id'=>$supp['supp_id']],'suppliers_id');
            //添加商品数据
            $data['goods_name']   = $arr['title'];          //名称
            $data['cn_name']      = $arr['cn_name'];        //中文名称
            $data['goods_sn']     = $arr['goods_sn'];       //货号
            $data['type_id']      = $arr['type_id'];        //类型ID  
            $data['cat_id']       = $arr['cate_id'];        //分类id
            $data['goods_weight'] = $arr['goods_weight'];   //重量
            $data['in_price']     = $arr['in_price'];       //进价
            $data['shop_price']   = $arr['shop_price'];     //价格
            $data['market_price'] = $arr['market_price'];   //市场价
            $data['g_supp_id']    = $suppliers_id['suppliers_id']; //供应商id
            $data['suppliers_id'] = $supp['supp_id'];       //supp表supp_id
            $data['supp_url']     = $arr['ali_url'];        //1688url
            $data['supp_sn']      = $supp['supp_sn'];       //supp表supp_sn
            $data['original_img'] = $arr['original_img'];   //主图
            $data['body_html']    = $arr['body_html'];      //内容
            $data['goods_attr']   = $arr['goods_attr'];     //属性
            $data['tags']         = $tag;                   //tag
            $data['admin_id']     = $arr['admin_id'];       //开发员
            $data['add_time']     = time();                 //添加时间
            $data['channel_id']   = $arr['channel_id'];     //渠道
            $data['fabric_id']    = $arr['fabric_id'];      //面料
            $data['purchase_id']  = $arr['purchase_id'];    //采购员ID
            $data['sale_status']  = $arr['sale_status'];    //销售状态
            $data['type_style']  = $arr['type_style'];    //风格
            $this->db->insert('goods',$data);
            $gid = $this->db->insert_id('goods');
        }
            //图片表加上goods_id
            $this->db->where(['prepare_id'=>$goods_id]);
            $this->db->update('goods_album',['goods_id'=>$gid]);
            //supp表加上goods_id
            $this->db->where(['prepare_id'=>$goods_id]);
            $this->db->update('goods_supp',['goods_id'=>$gid]);
            //SKU表加上goods_id
            $this->db->where(['prepare_id'=>$goods_id]);
            $this->db->update('goods_sku',['goods_id'=>$gid]);
            //prepare_option表加上goods_id
            $this->db->where(['prepare_id'=>$goods_id]);
            $this->db->update('prepare_option',['goods_id'=>$gid]);
            
            //查询sku   
            $query = $this->db->from('goods_sku')->where(['prepare_id'=>$goods_id])->get();
            $sku = $query->result_array();
            // print_R($sku);die;
            //查询类型
            $type = $this->select_find('goods_type',['cat_id'=>$arr['type_id']],'cat_name,cat_name_zh,cate_code');
            //供应商代码
            $supp_id = $this->select_find('goods_supp',['prepare_id'=>$goods_id],'supp_id');
            $e_code = $this->select_find('suppliers',['suppliers_id'=>$supp_id['supp_id']],'e_code,suppliers_name,suppliers_id');
            // print_R($e_code);die;
            if(empty($e_code['e_code'])){
                //code不存在查询E仓信息
                $supplierName = $this->eccang->getSupplierInfo(['condition'=>['supplierName'=>$e_code['suppliers_name']]]);
                // print_r($supplierName);die;
                if(empty($supplierName['data'])){
                    // if($e_code['suppliers_id'] % 2 == 1){
                    //     $buyerId = 583;
                    // }else{
                    //     $buyerId = 564;
                    // }
                    $data = ['actionType'=>'ADD','supplier'=>[
                        'supplierCode'=>'G'.$suppliers['suppliers_id'],
                        'supplierName'=>$suppliers['suppliers_name'],
                        'buyerId'=>$arr['purchase_id'],
                        'level'=>'A',
                        'supplierTeamworkType'=>0,
                        'supplierType'=>1,
                        'pcId'=>3,
                        'accountType'=>2,
                        'payType'=>1,
                        'supplierCarrier'=>1,
                        'shippingMethodIdHead'=>2,
                        'supplierQcException'=>2,
                        'accountProportion'=>100
                    ]];
                    $re = $this->eccang->syncSupplierInfo($data);
                    $e_code['e_code'] = $re['data']['supplierCode'];
                }else{
                    $e_code['e_code'] = $supplierName['data'][0]['supplierCode'];
                }
                //修改供应商 e_code
                $this->db->where(['suppliers_name'=>$e_code['suppliers_name']]);
                $this->db->update('suppliers',['e_code'=>$e_code['e_code']]);
            }
            // echo $e_code['e_code'];die;
            
            // // //循环添加 E 仓 
            // foreach ($sku as $k => $v) {
            //     //获取图片
            //     $album_url = $this->select_find('prepare_option',['option_value'=>$v['color'],'prepare_id'=>$v['prepare_id']],'album_url');
            //     $album_url = base_url().substr($album_url['album_url'],1);
            //     //E仓查询颜色ID
            //     $e_color_id = $this->select_find('colors',['color_en'=>$v['color']],'e_id');
            //     //E仓查询尺寸ID
            //     $e_size_id = $this->select_find('size',['size_value'=>$v['size']],'e_id');
            //     $eccang['actionType']            =  'ADD';
            //     $eccang['productSku']            =  $v['sku_sn'];                                                              //产品SKU
            //     $eccang['productTitle']          =  $arr['cn_name'] . $v['color'].'/'.$v['size'];                              //产品名称
            //     $eccang['productTitleEn']        =  $arr['title'];                                                             //产品英文名称
            //     $eccang['productWeight']         =  ($arr['goods_weight'] / 1000) < 0.01 ? 0.01 : $arr['goods_weight'] / 1000; //重量
            //     $eccang['pdOverseaTypeCn']       =  $type['cat_name_zh'];                                                      //中文申报品名
            //     $eccang['pdOverseaTypeEn']       =  $type['cat_name'];                                                         //英文申报品名
            //     $eccang['productDeclaredValue']  =  1.5;                                                                       //申报价值
            //     $eccang['pdDeclareCurrencyCode'] =  'USD';                                                                     //申报币种
            //     $eccang['productPurchaseValue']  =  $arr['in_price'];                                                          //采购价
            //     $eccang['currencyCode']          =  'RMB';                                                                     //采购币种
            //     $eccang['defaultSupplierCode']   =  $e_code['e_code'];                                                     //默认供应商代码
            //     $eccang['productPrice']          =  $arr['shop_price'];                                                        //销售价格
            //     $eccang['spProductAddress']      =  $arr['ali_url'];                                                       //供应商产品地址
            //     $eccang['productColorId']        =  $e_color_id['e_id'];                                                       //产品颜色
            //     $eccang['productSizeId']         =  $e_size_id['e_id'];                                                        //尺寸
            //     $eccang['hsCode']                =  $v['cate_code'];                                                           //海关申报代码
            //     $eccang['productImgUrlList']     =  [$album_url];                                                              //产品图片
            //     $eccang['saleStatus']            =  2;                                                                         //销售状态
            //     $eccang['productLength']         =  30;
            //     $eccang['productWidth']          =  25;
            //     $eccang['productHeight']         =  3;
            //     //添加 E 站SKU  
            //     $this->eccang->add_syncProduct($eccang);
            // }
        
    }

    //查看所有的log
    public function select_log($id){
        $this->config->load('website_common');
        $examine_type = $this->config->item('examine_type');
        $this->db->from('prepare_log');
        $this->db->where(['prepare_id'=>$id]);
        $this->db->select('add_time,admin_id,type_state');
        $query = $this->db->get();
        $prepare = $query->result_array();
        foreach ($prepare as $k => $v) {
            $arr = ['admin_id'=>$v['admin_id']];
            $admin_name = $this->select_find('admin',$arr,'admin_name');
            $prepare[$k]['admin_id'] = $admin_name['admin_name'];
            $prepare[$k]['add_time'] = date('Y-m-d H:i',$v['add_time']);
            $prepare[$k]['examine_type'] = $examine_type[$v['type_state']];
            
        }
        return $prepare;
    }
    //回收
    public function recovery($data){
        //查询商品当前状态
        $prepare_state = $this->select_find('prepare_goods',['prepare_id'=>$data['goods_id']],'prepare_state');
        //修改状态
        $this->db->where(['prepare_id'=>$data['goods_id']]);
        $this->db->update('prepare_goods',['prepare_state'=>6]);
        //添加日志记录
        return $this->add_log($data['goods_id'],$prepare_state['prepare_state'],6,6,$data['reason_reason']);
        
    }
    
    //还原
    public function reduction($data){
        //查询之前状态
        $order = 'log_id DESC';
        $before_state = $this->select_find('prepare_log',['prepare_id'=>$data['goods_id']],'before_state',$order);
        //还原商品状态
        $this->db->where(['prepare_id'=>$data['goods_id']]);
        $this->db->update('prepare_goods',['prepare_state'=>$before_state['before_state']]);
        //添加日志记录
        return $this->add_log($data['goods_id'],6,$before_state['before_state'],7,$data['reason_text']);
    }

    //添加日志记录
    //type_state  1 创建商品 2 编辑商品 3 补充商品 4 审核通过 5 审核不通过 6 加入回收站 7 撤回回收站 8 添加尺码 9 上架完成 10 加色
    public function add_log($prepare_id,$before_state,$current_state,$type_state,$content){
        $result['admin_id']      = $_SESSION['admin_id'];      //admin_id
        $result['prepare_id']    = $prepare_id;                //goods_id
        $result['before_state']  = $before_state;              //之前状态
        $result['current_state'] = $current_state;             //当前状态
        $result['type_state']    = $type_state;                //操作类型
        $result['content']       = $content;                   //操作原因
        $result['add_time']      = time();                     //添加时间
        $this->db->set($result);
        return $this->db->insert('prepare_log');
    }

    //准入表列表分页
    public function prepare_num($param = array())
    {
        if($param['admin_id'] > 0){
            $this->db->where(['admin_id'=>$param['admin_id']]);
        }
        if(!empty($param['goods_sn'])){
            $this->db->where(['goods_sn'=>$param['goods_sn']]);
        }
        if($param['cate_name'] > 0){
            $this->db->where(['cate_id'=>$param['cate_name']]);
        }
        if($param['production'] > 0){
            $this->db->where(['production_id'=>$param['production']]);
        }
        $this->db->where(['prepare_state'=>$param['prepare_state']]);


        if($param['prepare_state'] == 1 || $param['prepare_state'] == 2 || $param['prepare_state'] == 6){
            $len = 'prepare_id,original_img,goods_sn,prepare_state,cate_id,add_time,admin_id,production_id';
        }

        if($param['prepare_state'] == 3 || $param['prepare_state'] == 4 || $param['prepare_state'] == 5){
            $len = 'prepare_id,original_img,goods_sn,prepare_state,cate_id,add_time,admin_id,
            production_id,source_url,g_supp_id,channel_id,in_price,goods_weight,title';
        }

        $this->db->from('prepare_goods');
        //$this->db->where("cate_name LIKE '%{$param['cate_name']}%'");
        //$this->_where($param);
        return $this->db->count_all_results();
    }

    //查询记录表
    public function prepare_log($where,$find){
        $query = $this->db->from('prepare_log')->select($find)->where($where)->get();
        return $prepare = $query->row_array();
    }

    public function size_color($where,$len){
        $query = $this->db->from('prepare_option')->select($len)->where($where)->get();
        $option = $query->result_array();
        $res = '';
        if(!empty($option)){
            foreach ($option as $k => $v) {
                $res = $res.','.$v['option_value'];
            }
        }
        return $res;
        
    }

    //查询表
    public function prepare_table($table,$where,$find){
        $query = $this->db->from($table)->select($find)->where($where)->get();
        return $prepare = $query->result_array();
    }

    //查询数据
    public function select_find($table,$arr,$find,$order = ''){
        if(!empty($order)){
            $this->db->order_by($order);
        }
        $category_name = $this->db->from($table)->select($find)->where($arr)->get();
        $arr = $category_name->row_array();
        return $arr;
    }

    //修改goods_supp 加色
    public function supp_update($prepare_id,$arr){
        $this->db->where("prepare_id = '$prepare_id'");
        $this->db->update('goods_supp',['post_sku'=>json_encode($arr)]);
        //把option的数组全部下架
        $this->db->where("prepare_id = '$prepare_id'");
        $this->db->update('prepare_option',['is_delete'=>1]);
        //颜色查询存在修改 不寻在添加
        foreach ($arr['color'] as $color_k => $color_v){
            if(!empty($color_v['ali_value']) && !empty($color_v['value'])){
                $where = ['prepare_id'=>$prepare_id,'option_value'=>$color_v['value'],'ali_value'=>$color_v['ali_value']];
                $option_id = $this->select_find('prepare_option',$where,'option_id');
                if(!empty($option_id['option_id'])){
                    $this->db->where("prepare_id = '$prepare_id'");
                    $this->db->update('prepare_option',['is_delete'=>0]);
                }else{
                    $res['type_id'] = 1;
                    $res['option_value'] = $color_v['value'];
                    $res['add_time'] = time();
                    $res['prepare_id'] = $prepare_id;
                    $res['ali_value'] = $color_v['ali_value'];
                    $this->db->insert('prepare_option', $res);
                }
            }
        }
        //尺寸查询存在修改 不寻在添加
        foreach ($arr['size'] as $size_k => $size_v){
            if(!empty($size_v['ali_value']) && !empty($size_v['value'])){
                $where = ['prepare_id'=>$prepare_id,'option_value'=>$size_v['value'],'ali_value'=>$size_v['ali_value']];
                $option_id = $this->select_find('prepare_option',$where,'option_id');
                if(!empty($option_id['option_id'])){
                    $this->db->where("prepare_id = '$prepare_id'");
                    $this->db->update('prepare_option',['is_delete'=>0]);
                }else{
                    $res['type_id'] = 2;
                    $res['option_value'] = $size_v['value'];
                    $res['add_time'] = time();
                    $res['prepare_id'] = $prepare_id;
                    $res['ali_value'] = $size_v['ali_value'];
                    $this->db->insert('prepare_option', $res);
                }
            }
        }

    }

    //加色  废弃
    public function index_add_color($prepare_id,$arr){
        return false;
        //把SKU的数组全部下架
        $this->db->where("prepare_id = '$prepare_id'");
        $this->db->update('goods_sku',['is_delete'=>1]);
        //查询价钱
        $shop_price = $this->select_find('prepare_goods',['prepare_id'=>$prepare_id],'shop_price,goods_sn');
        foreach ($arr as $k => $v) {
            //如果没查询到添加行的SKU 否则修改
            $sku_id = $this->select_find('goods_sku',['specid'=>$v['specid']],'sku_id');
            if(empty($sku_id['sku_id'])){
                //查询色生成编码
                $col = $this->select_find('colors',['color_en'=>$v['color']],'option_id,color_on');
                $siz = $this->select_find('size',['size_value'=>$v['size']],'size_on');
                $sku_num_sn = $shop_price['goods_sn'].$col['option_id'].$col['color_on'].$siz['size_on'];
                //添加
                $v['prepare_id'] = $prepare_id;
                $v['add_time'] = time();
                $v['shop_price'] = $shop_price['shop_price'];
                $v['sku_num_sn'] = $sku_num_sn;
                $v['sku_sn'] = $sku_num_sn;
                $this->db->insert('goods_sku', $v);
            }else{
                //修改
                $this->db->where(['specid'=>$v['specid']]);
                $this->db->update('goods_sku',['is_delete'=>0]);
            }
        }
        //添加日志
        $this->add_log($prepare_id,5,4,10,'加色');
        //加色回到上架待审核
        $this->db->where(['prepare_id'=>$prepare_id]);
        $this->db->update('prepare_goods',['prepare_state'=>4]);
    }

    //复购率
    public function color_complex($_param){
        if(!empty($_param['add_time_start'])){
            $add_time_start = strtotime($_param['add_time_start']);
            $add_time_end = strtotime($_param['add_time_end']);
            $this->db->where('add_time >',$add_time_start);
            $this->db->where('add_time <',$add_time_end);
        }

        if(!empty($_param['coupon_code'])){
            $this->db->where(['coupon_code'=>$_param['coupon_code']]);
        }else{
            $this->db->where ('coupon_code !=','');
        }
        $this->db->where ('email !=','');
        
        $f_cun = $this->db->count_all_results('order_info', FALSE);

        $d_cun = $this->db->count_all('order_info');

        $cunst_s = $f_cun / $d_cun * 100;

        //总数
        if(!empty($_param['add_time_start'])){
            $add_time_start = strtotime($_param['add_time_start']);
            $add_time_end = strtotime($_param['add_time_end']);
            $this->db->where('add_time >',$add_time_start);
            $this->db->where('add_time <',$add_time_end);
        }

        if(!empty($_param['coupon_code'])){
            $this->db->where(['coupon_code'=>$_param['coupon_code']]);
        }else{
            $this->db->where ('coupon_code !=','');
        }
        $this->db->where ('email !=','');

        $this->db->from('order_info');
        $this->db->select('order_amount,discounts_amount,goods_amount');
        $this->db->order_by('add_time desc');
        $query = $this->db->get();
        $prepare = $query->result_array();
        $order_amount_count = 0;
        $discounts_amount_count = 0;
        $goods_amount_count = 0;
        foreach ($prepare as $k => $v) {
            $order_amount_count = $order_amount_count + $v['order_amount'];
            $discounts_amount_count = $discounts_amount_count + $v['discounts_amount'];
            $goods_amount_count = $goods_amount_count + $v['goods_amount'];
        }

        //列表
        if(!empty($_param['add_time_start'])){
            $add_time_start = strtotime($_param['add_time_start']);
            $add_time_end = strtotime($_param['add_time_end']);
            $this->db->where('add_time >',$add_time_start);
            $this->db->where('add_time <',$add_time_end);
        }

        if(!empty($_param['coupon_code'])){
            $this->db->where(['coupon_code'=>$_param['coupon_code']]);
        }else{
            $this->db->where ('coupon_code !=','');
        }
        $this->db->where ('email !=','');
        $this->db->from('order_info');
        $this->db->limit($this->limit_rows,$this->limit_rows * $_param['page']);
        $this->db->select('order_sn,order_amount,discounts_amount,goods_amount,coupon_code,order_sn,order_id');
        $this->db->order_by('add_time desc');
        $query = $this->db->get();
        $prepare = $query->result_array();
        foreach ($prepare as $k => $v) {
            $prepare[$k]['goods_name'] = $this->prepare_table('order_goods',['order_id'=>$v['order_id']],'goods_name,goods_attr');
        }
        return [
            'count'=>$f_cun,
            'count_s'=>$d_cun,
            'cunst_s'=>$cunst_s,
            'prepare'=>$prepare,
            'order_amount_count'=>$order_amount_count,
            'discounts_amount_count'=>$discounts_amount_count,
            'goods_amount_count'=>$goods_amount_count
        ];
    }


    //复购率列表分页
    public function prepare_complex($_param = array())
    {
        if(!empty($_param['add_time_start'])){
            $add_time_start = strtotime($_param['add_time_start']);
            $add_time_end = strtotime($_param['add_time_end']);
            $this->db->where('add_time >',$add_time_start);
            $this->db->where('add_time <',$add_time_end);
        }

        if(!empty($_param['coupon_code'])){
            $this->db->where(['coupon_code'=>$_param['coupon_code']]);
        }else{
            $this->db->where ('coupon_code !=','');
        }
        $this->db->where ('email !=','');
        $this->db->from('order_info');
        return $this->db->count_all_results();
    }
    public function prepare_update($data = array(), $prepare_state, $prepare_id) {

        $time = time();

        $_goods_supp = array();
        $_prepare = array();
        $_option = array();

        switch ($prepare_state) {
            case 3:
                $_prepare = array(
                    'ali_url' => $data['supp_url'],
                    'g_supp_id' => $data['g_supp_id'],
                    'shop_price' => $data['shop_price'],
                    'in_price' => $data['in_price']
                );

                $_goods_supp = array(
                    'cn_name' => $data['supp_name'],
                    'supp_url' => $data['supp_url'],
                    'supp_sn' => $data['supp_sn'],
                    'in_price' => $data['in_price'],
                    'prepare_id' => $prepare_id
                );
                $this->add_prepare_log($prepare_state, 2, '产品补充', $prepare_id);
                break;
            case 4:
                $_prepare = array(
                    'title' => $data['title'],
                    'cn_name' => $data['cn_name'],
                    'type_id' => $data['type_id'],
                    'goods_weight' => $data['goods_weight'],
                    'shop_price' => $data['shop_price'],
                    'is_testing' => $data['is_testing'],
                    'body_html' => $data['body_html'],
                    'goods_attr' => json_encode($data['goods_attr']),
                    'tags' => $data['tags'],
                    'purchase_id' => $data['purchase_id']
                );

                $_goods_supp['supp_id'] = $data['suppliers_id'];
                $this->add_prepare_log($prepare_state, 3, '产品编辑', $prepare_id);
                break;
        }


        if ($data['images']) {

            $_images = array();
            $i = 0;
            foreach ($data['images'] as $k => $image) {

                switch ($image['handle']) {
                    case 'update':
                        $_images['update'][] = array(
                            'album_sort' => $i,
                            'album_id' => $image['album_id']
                        );
                        break;
                    case 'insert':
                        $_images['insert'][] = array(
                            'prepare_id' => $prepare_id,
                            'sku_id' => 0,
                            'original_img' => $image['file_name'],
                            'big_img' => '',
                            'small_img' => '',
                            'width' => $image['image_width'],
                            'height' => $image['image_height'],
                            'album_sort' => $i,
                            'is_delete' => 0,
                            'add_time' => $time
                        );
                        break;
                    case 'delete':
                        $_images['update'][] = array(
                            'album_id' => $image['album_id'],
                            'album_sort' => $i,
                            'is_delete' => 1
                        );
                        break;
                }
                $i++;
            }

        }

        if ($data['option']) {
            foreach ($data['option'] as $k => $op_val) {

                $_option['update'][] = array(
                    'option_id' => $k,
                    'album_url' => $op_val['album_url']
                );
            }

        }

        if ($data['ali_sku']) {
            $_goods_supp['post_sku'] = json_encode($data['ali_sku']);
            foreach ($data['ali_sku'] as $k => $val) {
                $_type_id = $k == 'color' ? 1 : 2;
                foreach ($val as $row) {
                    if ($row['value'] != '') {
                        $_option['insert'][] = array(
                            'prepare_id' => $prepare_id,
                            'type_id' => $_type_id,
                            'option_value' => $row['value'],
                            'ali_value' => $row['ali_value'],
                            'add_time' => $time
                        );
                    }
                }
            }
        }

        if ($_option['update']) {
            $this->db->update_batch('prepare_option', $_option['update'], 'option_id');
        }
        if ($_option['insert']) {
            $this->db->insert_batch('prepare_option', $_option['insert']);
        }

        if ($data['sku']) {
            $_goods_sku = array();

            foreach ($data['sku'] as $k => $v) {

                $size = trim($v['size']);
                $color = trim($v['color']);
                $ali_color = $this->db->from('prepare_option')
                        ->where(['prepare_id'=>$prepare_id,'option_value'=>$color])
                        ->select('ali_value,album_url')
                        ->get()->row_array();
                $ali_size = $this->db->from('prepare_option')
                        ->where(['prepare_id'=>$prepare_id,'option_value'=>$size])
                        ->select('ali_value')
                        ->get()->row_array();
                switch ($v['handle']) {
                    case 'insert':
                        $_goods_sku['insert'][] = array(
                            'sku_sn' => $v['sku_sn'],
                            'sku_num_sn' => strval($v['sku_num_sn']),
                            'prepare_id' => $prepare_id,
                            'specid' => $v['specid'],
                            'color' => $color,
                            'size' => $size,
                            'inventory_policy' => 0,
                            'sku_number' => 0,
                            'shop_price' => $data['shop_price'],
                            'is_delete' => 0,
                            'update_time' => $time,
                            'add_time' => $time,
                            'shopify_id' => 0,
                            'ali_color' => $ali_color['ali_value'],
                            'ali_size' => $ali_size['ali_value'],
                            'album_url' => $ali_color['album_url']
                        );
                        break;
                    case 'delete':
                        $_goods_sku['update'][] = array(
                            'sku_id' => $v['sku_id'],
                            'is_delete' => 1
                        );
                    case 'update':
                        $_goods_sku['update'][] = array(
                            'sku_id' => $v['sku_id'],
                            'specid' => $v['specid']
                        );
                        break;
                }

            }
        }

        

        if ($_prepare) {

            $_prepare['prepare_state'] = $prepare_state;

            $this->db->where("prepare_id = '$prepare_id'");
            $this->db->update('prepare_goods',$_prepare);
        }
        

        if ($_goods_sku['insert']) {
            $this->db->insert_batch('goods_sku', $_goods_sku['insert']);
        }
        if ($_goods_sku['update']) {
            $this->db->update_batch('goods_sku', $_goods_sku['update'], 'sku_id');
        }

        if ($_images['insert']) {
            $this->db->insert_batch('goods_album', $_images['insert']);
        }
        if ($_images['update']) {
            $this->db->update_batch('goods_album', $_images['update'], 'album_id');
        }

        if ($_goods_supp && $data['g_supp_id']) {
            $this->db->where("g_supp_id = '{$data['g_supp_id']}'");
            $this->db->update('goods_supp',$_goods_supp);
        }

        

        return true;

    }

    public function goods_supp_info($prepare_id)
    {
        $query = $this->db->from('goods_supp')->where('prepare_id', $prepare_id)->get();

        $info = $query->row_array();

        $info['goods_json'] = json_decode($info['goods_json'], true);

        return $info;
    }

    public function goods_album($prepare_id)
    {
        $query = $this->db->from('goods_album')->where("prepare_id = '$prepare_id' and is_delete = 0")->get();

        $_list = $query->result_array();

        $list = array();
        foreach ($_list as $row) {
            $list[$row['album_id']] = $row;
        }

        return $list;
    }

    public function goods_option($prepare_id)
    {
        $query = $this->db->from('prepare_option')
            ->where("prepare_id = '{$prepare_id}' and is_delete = 0")
            ->get();

        $_list = $query->result_array();

        $list = array();
        foreach ($_list as $item) {
            $list[$item['option_id']] = $item;
        }

        return $list;
    }

    public function goods_sku($prepare_id)
    {
        $query = $this->db->from('goods_sku')
            ->where("prepare_id = '{$prepare_id}' and is_delete = 0")
            ->get();

        $_list = $query->result_array();

        foreach ($_list as $item) {
            $list[$item['sku_num_sn']] = $item;
        }

        return $list;
    }

    public function add_prepare_log($prepare_state, $type_state, $content, $prepare_id)
    {
        $info = $this->info($prepare_id);

        $this->db->where('prepare_id', $prepare_id);
        $this->db->update('prepare_goods', array(
            'prepare_state' => $prepare_state
        ));

        $data_log = array(
            'admin_id' => intval($_SESSION['admin_id']),
            'prepare_id' => $prepare_id,
            'before_state' => intval($info['before_state']),
            'current_state' => $prepare_state,
            'type_state' => $type_state,
            'content' => $content,
            'add_time' => time(),
        );
        $this->db->insert('prepare_log', $data_log);
    }

    public function info($prepare_id)
    {
        $query = $this->db->from('prepare_goods')->where('prepare_id', $prepare_id)->get();

        $info = $query->row_array();

        return $info;
    }
}
